package services

import (
	"fmt"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"time"
)

type CustomerService struct {
}

// GetCustomerInfoByUnifySocialCreditCode 根据统一标识获取客户信息 -- 登录使用
func (customer CustomerService) GetCustomerInfoByUnifySocialCreditCode(UnifySocialCreditCode string) (models.WzjCustomerInfo, error) {
	var wzjCustomerInfo models.WzjCustomerInfo
	sql := "SELECT id,unify_social_credit_code,customer_pwd,customer_name FROM wzj_db.wzj_customer_info WHERE (unify_social_credit_code = ? or customer_account = ?);"
	if err := db.Raw(sql, UnifySocialCreditCode, UnifySocialCreditCode).Limit(1).Find(&wzjCustomerInfo).Error; err != nil {
		log.Error("GetCustomerInfoByUnifySocialCreditCode---根据名称查询律师信息失败：", err)
		return wzjCustomerInfo, err
	}
	return wzjCustomerInfo, nil
}

// 根据条件获取客户列表
func (customer CustomerService) GetCustomerList(userid int, isLaw bool, customerListReq dto.CustomerListReq) ([]models.WzjCustomerInfo, int64, error) {
	var wzjCustomerInfosList []models.WzjCustomerInfo
	tx := db.Where("1=1")
	if customerListReq.CustomerType != 0 {
		tx = tx.Where(" customer_type = ? ", customerListReq.CustomerType)
	}
	if len(customerListReq.CustomerName) > 0 {
		tx = tx.Where(" customer_name like ? ", "%"+customerListReq.CustomerName+"%")
	}
	if len(customerListReq.CustomerAccountManagers) > 0 {
		tx = tx.Where(" customer_account_managers like ? ", "%"+customerListReq.CustomerAccountManagers+"%")
	}
	if !isLaw {
		//增加共享客户显示
		tx = tx.Where(" (id  = ? or customer_share=1) ", userid)
	}
	dataCount := int64(0)
	if err := tx.Count(&dataCount).
		Select("id,unify_social_credit_code,customer_pwd,customer_name,customer_code,create_date,customer_status,customer_type,customer_account_managers").
		Limit(int(customerListReq.PageSize)).Offset(int((customerListReq.PageIndex - 1) * customerListReq.PageSize)).
		Order("create_date desc").
		Find(&wzjCustomerInfosList).Error; err != nil {
		log.Error("GetCustomerList---根据条件获取客户列表失败：", err)
		return wzjCustomerInfosList, dataCount, err
	}
	return wzjCustomerInfosList, dataCount, nil
}

// CreateCustomer 创建客户信息
func (customer CustomerService) CreateCustomer(wzjCustomerInfo models.WzjCustomerInfo, wzjCustomerInvoice models.WzjCustomerInvoice, wzjCustomerLegal models.WzjCustomerLegal) (bool, error) {
	tx := db.Begin()
	yearCustomerCount := int64(0)
	if err := db.Table("wzj_db.wzj_customer_info").Where(" FROM_UNIXTIME(create_date,'%Y') = DATE_FORMAT(NOW(),'%Y') ").Count(&yearCustomerCount).Error; err != nil {
		return false, err
	}
	if time.Now().Year() == 2021 {
		yearCustomerCount += 195
	}
	wzjCustomerInfo.CustomerCode = fmt.Sprintf("%s%s", wzjCustomerInfo.CustomerCode, fmt.Sprintf("%06d", yearCustomerCount+1))
	wzjCustomerInfo.IsEnabled = 1 //默认有效
	if err := tx.Create(&wzjCustomerInfo).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	wzjCustomerInvoice.CustomerId = wzjCustomerInfo.Id
	if err := tx.Create(&wzjCustomerInvoice).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	wzjCustomerLegal.CustomerId = wzjCustomerInfo.Id
	if err := tx.Create(&wzjCustomerLegal).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return false, err
	}
	return true, nil
}

// UpdateCustomer 更新客户信息
func (customer CustomerService) UpdateCustomer(wzjCustomerInfo models.WzjCustomerInfo, wzjCustomerInvoice models.WzjCustomerInvoice, wzjCustomerLegal models.WzjCustomerLegal) (bool, error) {
	tx := db.Begin()
	if err := tx.Where("id = ?", wzjCustomerInfo.Id).Select("unify_social_credit_code,customer_account,customer_pwd,customer_name,customer_status,customer_type,customer_address,customer_mobile,customer_fax,customer_from_id,customer_from,customer_share,customer_level,customer_account_managers_id,customer_account_managers,customer_owner").
		Updates(&wzjCustomerInfo).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	wzjCustomerInvoice.CustomerId = wzjCustomerInfo.Id
	if err := tx.Where("customer_id=?", wzjCustomerInfo.Id).Select("invoice_address,invoice_bank_deposit,invoice_bank_account_number").Updates(&wzjCustomerInvoice).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	wzjCustomerLegal.CustomerId = wzjCustomerInfo.Id
	if err := tx.Where("customer_id=?", wzjCustomerInfo.Id).Select("legal_name,legal_id_card,legal_post").Updates(&wzjCustomerLegal).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return false, err
	}
	return true, nil
}

// GetCustomerInfoById 根据统一标识获取客户信息 -- 登录使用
func (customer CustomerService) GetCustomerInfoById(id int) (models.WzjCustomerInfo, models.WzjCustomerInvoice, models.WzjCustomerLegal, error) {
	var wzjCustomerInfo models.WzjCustomerInfo
	var wzjCustomerInvoice models.WzjCustomerInvoice
	var wzjCustomerLegal models.WzjCustomerLegal
	sql := "SELECT id,unify_social_credit_code,customer_pwd,customer_account,customer_name,customer_status,customer_type,customer_address,customer_mobile,customer_fax,customer_from,customer_share,customer_level,customer_account_managers,customer_owner,create_date FROM wzj_db.wzj_customer_info WHERE id = ?;"
	if err := db.Raw(sql, id).Find(&wzjCustomerInfo).Error; err != nil {
		log.Error("根据名称查询律师信息失败：", err)
	}
	sql = "SELECT customer_id,invoice_address,invoice_bank_deposit,invoice_bank_account_number FROM wzj_db.wzj_customer_invoice WHERE customer_id = ?;"
	if err := db.Raw(sql, id).Find(&wzjCustomerInvoice).Error; err != nil {
		log.Error("根据名称查询律师信息失败：", err)
	}
	sql = "SELECT customer_id,legal_name,legal_id_card,legal_post FROM wzj_db.wzj_customer_legal WHERE customer_id = ?;"
	if err := db.Raw(sql, id).Find(&wzjCustomerLegal).Error; err != nil {
		log.Error("根据名称查询律师信息失败：", err)
	}
	return wzjCustomerInfo, wzjCustomerInvoice, wzjCustomerLegal, nil
}

// GetCustomerInfoForSelectByOwner 根据当前登录人获取名下的所有客户信息
func (customer CustomerService) GetCustomerInfoForSelectByOwner(ownerId, customerType int, isLaw bool) ([]models.SelectValue, error) {
	var list []models.SelectValue
	tx := db
	if !isLaw && customerType == 1 {
		//不是律师，也不是当事人，则查询本身
		tx = tx.Where("id=?", ownerId)
	} else if isLaw {
		if customerType != 0 {
			tx = tx.Where(" customer_type = ?", customerType)
		}
		law := LawService{}
		_law := models.WzjLawInfo{
			Id: int64(ownerId),
		}
		wzjLawInfo, _ := law.GetLawByCondition(_law)
		if wzjLawInfo.LawRole == 2 || wzjLawInfo.LawRole == 3 {
			tx = tx.Where(" (customer_account_managers_id = ? or customer_share=1)", ownerId)
		}
	}
	if err := tx.Select(" id 'value',customer_name 'label' ").Find(&list).Error; err != nil {
		log.Error("GetCustomerInfoForSelectByOwner -- 根据当前登录人获取名下的所有客户信息失败：", err)
		return list, err
	}
	return list, nil
}
